// src/api/modules/order.js
import request from "../request";

export default {
  /**
   * 创建订单
   * @param {Object} orderData - { houseId: number, customerId: number, startDate: string, endDate: string }
   */
  createOrder(orderData) {
    if (!orderData.houseId || typeof orderData.houseId !== "number") {
      throw new Error("房源ID必须为数值类型");
    }
    return request.post("/api/order/createOrder", orderData);
  },

  /**
   * 支付订单
   * @param {number} orderId - 订单ID
   */
  payOrder(orderId, houseId) {
    return request.post(`/api/order/payOrder/${orderId}/${houseId}`);
  },

  /**
   * 确认订单
   * @param {number} orderId - 订单ID
   */
  confirmOrder(orderId) {
    return request.put(`/api/order/confirmOrder/${orderId}`);
  },

  /**
   * 获取订单列表（带分页）
   * @param {Object} params - {
   *   customerId?: number,
   *   ownerId?: number,
   *   houseId?: number,
   *   status?: number,
   *   page?: number,
   *   size?: number,
   *   sortField?: string,
   *   sortOrder?: string
   * }
   */
  getOrderList(params = {}) {
    // 参数处理
    const queryParams = {
      ...params,
      page: params.page || 1,
      size: params.size || 10,
    };

    // 删除空值参数
    Object.keys(queryParams).forEach((key) => {
      if (queryParams[key] === null || queryParams[key] === undefined) {
        delete queryParams[key];
      }
    });

    return request.get("/api/order/listOrders", {
      params: queryParams,
    });
  },
  getOrderDetail(id) {
    return request.get(`/api/order/getOrderDetail/${id}`);
  },
  cancelOrder(orderId, reason) {
    if (!orderId || typeof orderId !== "number") {
      throw new Error("订单ID必须为数值类型");
    }
    if (!reason || typeof reason !== "string") {
      throw new Error("取消原因不能为空");
    }
    return request.put(`/api/order/cancelOrder/${orderId}`, {
      reason: reason,
    });
  },
  refuseOrder(orderId, refusalReason) {
    return request.post(`/api/order/refuseOrder/${orderId}`, {
      refusalReason: refusalReason,
    });
  },
  agreeOrder(orderId) {
    return request.put(`/api/order/agreeOrder/${orderId}`);
  },
};
